import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: () => ({
    // 先从本地取
    token: getToken() || '',
    userInfo: {}
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 清除用户数据的方法
    removeUserInfo(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
      resetRouter()
    }
  },
  actions: {
    async asyncSetToken(ctx, data) {
      const res = await login(data)
      ctx.commit('setToken', res.data)
    },
    async asyncGetUserInfo(ctx) {
      const res = await getUserInfo()
      const resDetail = await getUserDetailById(res.data.userId)
      ctx.commit('setUserInfo', { ...res.data, ...resDetail.data })
      return { ...res.data, ...resDetail.data }
    }
  }
}
